#pragma once
#include <QThread>
#include <QObject>
#include <iostream>
#include <memory>
#include <SceneGraph/scene_graph.h>
#include <driver.h>
#include <time.h>

class Simulation :public QObject {
	Q_OBJECT

public:
	explicit Simulation(std::shared_ptr<PhysLeo::SceneGraph> scene_graph, std::shared_ptr<Driver> driver, float dt, QObject *parent = nullptr) :
    QObject(parent), 
    scene_graph_(std::move(scene_graph)), 
    driver_(std::move(driver)), 
    dt_(dt)
	{
	    
	}

signals:
	void updateWindow();
	void finished();

public slots:
	void start() {
        scene_graph_->initSimulationResourceGraph();
		while ( driver_->status_ != DriverStatus::FINISHED) { 
			if (driver_->status_ == DriverStatus::STOPPED)
				QThread::yieldCurrentThread();
			else if (driver_->status_ == DriverStatus::RUNNABLE) {
                auto start = clock();
                scene_graph_->runGraph(dt_);
                scene_graph_->transformDrawDataGraph();
                auto end = clock();
                const auto time_per_frame = static_cast<double>(end - start) / CLOCKS_PER_SEC;
                std::cout << "time per Frame:" << time_per_frame << std::endl;
				emit updateWindow();
			}
		}
		emit finished();	
	}

protected:
    std::shared_ptr<PhysLeo::SceneGraph> scene_graph_;
    std::shared_ptr<Driver> driver_;
    float dt_;
};